<template>
  <Main :type="'form'">
    <images
      :dialog-images="showImages"
      :use-btn="true"
      :use-type="'img'"
      @close="close"
    />
    <Title :title="pageName" />
    <el-steps :active="actives" simple style="margin-bottom:20px;">
      <el-step title="1. 价格信息" icon="el-icon-edit"></el-step>
      <el-step title="2. 规格设置" icon="el-icon-edit"></el-step>
      <el-step title="3. 产品详情" icon="el-icon-edit"></el-step>
    </el-steps>
    <el-row>
      <el-col :span="24">
        <el-form ref="form" label-width="130px" :rules="rules" :model="form">
          <div v-if="actives == 1">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input
                v-model="form.goods_name"
                placeholder="请输入商品名称"
                class="form-input"
                size="medium"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_type">
              <el-cascader
                v-model="form.goods_type"
                :props="defaultProps"
                :options="commodityClass"
                :show-all-levels="false"
                placeholder="请选择商品分类"
              >
              </el-cascader>
              <!-- &nbsp;&nbsp;&nbsp;
              <el-button
                size="mini"
                icon="el-icon-refresh-right"
                type="text"
                @click="getCommodityClass"
              >
              </el-button>
              <el-button size="mini" type="text" @click="addF">
                新建分类
              </el-button> -->
            </el-form-item>

            <el-form-item label="商品图片" prop="goods_cover">
              <div class="commodityImage clearfix">
                <div
                  v-for="(item, index) in form.goods_cover"
                  :key="index"
                  class="icon"
                  @dragstart.capture="dragstarts(index, $event)"
                  @drop.stop="drops(index, $event)"
                  @dragover.prevent="dragovers(item, index, $event)"
                >
                  <div>
                    <img
                      :src="$store.state.qiniu + item + $store.state.imgRotate"
                      alt=""
                    />
                  </div>
                  <div>
                    <i class="el-icon-delete delimg" @click="delImg(index)"></i>
                  </div>
                </div>
                <el-button type="primary" @click="showImages = true"
                  >选择图片</el-button
                >
              </div>
            </el-form-item>
            <el-form-item label="商品标签">
              <el-select v-model="form.tag_id" placeholder="请选择商品标签">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  class="options"
                >
                  <span class="l">{{ item.name }}</span>
                  <i
                    v-if="item.type !== 1"
                    class="r el-icon-error"
                    @click="delTag(item.id)"
                  ></i>
                </el-option>
              </el-select>
              &emsp;
              <el-button type="text" @click="dialogFormVisibleBQ = true"
                >新增</el-button
              >
              <el-button type="text" class="btsample"
                >查看示例
                <div class="sample">
                  <img
                    src="http://oss.ztwlxx.cn/%E5%9B%BE%E7%89%87.png"
                    width="100%"
                    height="100%"
                  />
                </div>
              </el-button>
            </el-form-item>
            <el-form-item label="原价" prop="">
              <el-input-number
                v-model="form.goods_price"
                :controls="false"
                :precision="2"
                :min="0"
                size="medium"
              ></el-input-number>
            </el-form-item>

            <!--
            <el-form-item label='成本价'
                          prop='commodityOriginalMoney'>
              <el-input class='form-input'
                        v-model='form.cost_rack'
                        :maxlength='8'></el-input>
            </el-form-item>
            <el-form-item label='市场价'
                          prop='commodityOriginalMoney'>
              <el-input class='form-input'
                        v-model='form.goods_original_price'
                        :maxlength='8'></el-input>
            </el-form-item> -->

            <el-form-item label="配送模式" prop="distribution_type">
              <el-checkbox-group v-model="form.distribution_type">
                {{ listPSMS }}
                <el-checkbox
                  v-for="(item, index) in listPSMS"
                  :key="index"
                  :label="item.label"
                  >{{ item.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>

            <el-form-item v-if="setM" label="设置配送模板" prop="templete_id">
              <el-select
                v-model="form.templete_id"
                class="form-input"
                placeholder="选择模板"
                @change="psTag"
              >
                <el-option
                  v-for="(item, index) in courierLsit"
                  :key="index"
                  :label="item.name"
                  :value="item.templete_id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="setM">
              <Table :data="tableData" style="width:80%;">
                <el-table-column
                  label="可配送区域"
                  width="400"
                  property="area_name"
                ></el-table-column>
                <el-table-column
                  :label="labelArr[0]"
                  property="first"
                ></el-table-column>
                <el-table-column
                  :label="labelArr[1]"
                  property="first_price"
                ></el-table-column>
                <el-table-column
                  :label="labelArr[2]"
                  property="continuation"
                ></el-table-column>
                <el-table-column
                  :label="labelArr[3]"
                  property="continuation_price"
                ></el-table-column>
              </Table>
            </el-form-item>
          </div>
          <div v-if="actives == 2">
            <specification
              :attr-data="attrData"
              :specification-data="specificationData"
              :title="'商品'"
              :type="form.goods_type"
              @returnData="returnData"
            />
          </div>

          <div v-if="actives == 3">
            <el-form-item label="商品详情" prop="goods_content">
              <div style=" width: 90%; height: 600px;">
                <rich-text-editor
                  :text="form.goods_content"
                  :heights="'500px'"
                  @editorChange="editorChange"
                />
              </div>
            </el-form-item>
            <el-form-item label="上架状态" prop="status">
              <el-select v-model="form.status" class="form-input">
                <el-option label="上架" value="normal"></el-option>
                <el-option label="暂不上架" value="temporarily"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
      </el-col>
    </el-row>
    <Footer>
      <el-button v-if="actives == 1" plain @click="$emit('out')"
        >取 消</el-button
      >
      <el-button v-else plain @click="submitup">上一步</el-button>
      <el-button v-if="actives != 3" type="primary" @click="submit"
        >下一步</el-button
      >
      <el-button v-else type="primary" @click="submit">保 存</el-button>
    </Footer>
    <el-dialog title="新建标签" :visible.sync="dialogFormVisibleBQ" width="30%">
      <el-form
        ref="formBQ"
        :model="formBQ"
        :rules="rulesBQ"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="formBQ.name"
            type="text"
            style="line-height: 20px;"
            placeholder="内容最多5个字"
            maxlength="5"
            show-word-limit
            size="medium"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleBQ = false">取 消</el-button>
        <el-button type="primary" @click.stop="setTag">确 定</el-button>
      </span>
    </el-dialog>
  </Main>
</template>
<script>
import {
  SETGOODS,
  TAGLIST,
  SETTAG,
  DELTAG,
  GOODSINFO,
  SHOWDISTRIBUTIONCONFIGShop,
  GETLISTShopClass
} from "../service";
import { DISTRIBUTIONTEMPLETELIST } from "@/service/shop";

export default {
  components: {
    images: r =>
      require.ensure([], () => r(require("publicCom/imgupdate")), "imgupdate"),
    richTextEditor: r =>
      require.ensure(
        [],
        () => r(require("publicCom/richTextEditor/richTextEditor")),
        "richTextEditor"
      ),
    specification: () => import("publicCom/specification")
  },
  props: {
    goodsId: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      actives: 1,
      pageName: "商品录入",
      specifications: [],
      specificationData: [], // 规格项目及规格值1
      attr_arr: [],
      attrData: [],
      commodityClass: [],
      form: {
        goods_name: "",
        goods_type: [],
        goods_cover: [],
        goods_price: "",
        cost_rack: "",
        goods_original_price: "",
        distribution_type: [],
        templete_id: "",
        goods_content: "",
        goods_stock: 0,
        status: "normal",
        tag_id: ""
      },
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_type: [
          { required: true, message: "请选择商品分类", trigger: "blur" }
        ],
        goods_cover: [
          { required: true, message: "请选择商品图片", trigger: "blur" }
        ],
        goods_content: [
          { required: true, message: "请输入商品详情", trigger: "blur" }
        ],
        goods_price: [{ type: "number", message: "年龄必须为数字值" }],
        templete_id: [
          { required: true, message: "请选择配送模板", trigger: "blur" }
        ],
        distribution_type: [
          { required: true, message: "请选择配送模式", trigger: "blur" }
        ],
        status: [{ required: true, message: "请输入商品详情", trigger: "blur" }]
      },
      imgShow: -1,
      options: [],
      formBQ: {
        name: ""
      },
      rulesBQ: {
        name: [{ required: true, message: "请输入标签名称", trigger: "blur" }]
      },
      dialogFormVisibleBQ: false,

      showImages: false,

      defaultProps: {
        value: "type_id",
        children: "second",
        label: "type_name"
      },
      defaultPropsCp: {
        value: "config_id",
        label: "cate_name"
      },

      courierLsit: [],
      tagLists: [],
      setM: false,
      listPSMS: [],
      labelArr: ["首件（个）", "运费（元）", "续件（个）", "续费（元）"],
      tableData: [],
      valuation: 1
    };
  },
  computed: {},
  watch: {
    "form.distribution_type"(v) {
      if (v) {
        this.setM = v.includes("1");
      }
    },
    valuation(v) {
      switch (v) {
        case 1:
          this.labelArr = [
            "首件（个）",
            "运费（元）",
            "续件（个）",
            "续费（元）"
          ];
          break;
        case 2:
          this.labelArr = [
            "首重（kg）",
            "运费（元）",
            "续重（kg）",
            "续费（元）"
          ];
          break;
        case 3:
          this.labelArr = [
            "首体积（m³）",
            "运费（元）",
            "续体积（m³）",
            "续费（元）"
          ];
          break;
      }
    }
  },
  created() {
    this.getCommodityClass();
    this.tagList();
    this.getPSMS();
    this.getMB();
    if (this.goodsId) {
      this.pageInit();
    }
  },
  methods: {
    imagesR(i) {
      this.imgShow = i;
    },
    imagesO() {
      this.imgShow = -1;
    },
    delImg(i) {
      this.form.goods_cover.splice(i, 1);
    },
    editorChange(html) {
      this.form.goods_content = html;
    },
    returnData(e) {
      this.specifications = e.specifications;
      this.attr_arr = e.attr_arrs;
    },
    dragstarts(index, e) {
      e.dataTransfer.setData("dataindex", index);
    },
    drops(index, e) {
      let getIndex = e.dataTransfer.getData("dataindex");
      let arrJson = this.form.goods_cover[getIndex];
      this.form.goods_cover.splice(getIndex, 1);
      this.form.goods_cover.splice(index, 0, arrJson);
    },
    dragovers() {},
    async pageInit() {
      await GOODSINFO({ goods_id: this.goodsId }).then(
        ({ code, data, msg }) => {
          if (code === 200) {
            this.form.goods_name = data.goods_name;
            this.form.goods_type = [
              data.goods_type.parent,
              data.goods_type.child
            ];
            this.form.goods_cover = data.goods_cover.split(",");
            this.form.goods_price = data.goods_price;
            this.form.tag_id = data.tag_id === "ZA%3D%3D" ? "" : data.tag_id;
            this.form.distribution_type = data.distribution_type.split(",");
            this.attrData = JSON.parse(data.attr_arr);
            this.specificationData = JSON.parse(data.sku_type);
            this.form.goods_content = data.goods_content;
            this.form.templete_id = data.templete_id;
            this.form.status = data.status;
          } else {
            this.$message.error(msg);
          }
        }
      );
    },

    async getCommodityClass() {
      await GETLISTShopClass().then(({ code, data }) => {
        if (code === 200) {
          this.commodityClass = data;
        }
      });
    },
    submitup() {
      this.$store.commit("imgInitPgae", 1);
      switch (this.actives) {
        case 2:
          this.actives = 1;
          break;
        case 3:
          this.actives = 2;
          break;
      }
    },
    async submit() {
      await this.$refs["form"].validate(valid => {
        if (valid) {
          this.$store.commit("imgInitPgae", 1);
          if (this.actives === 1) {
            this.actives = 2;
            return;
          }
          if (this.actives === 2) {
            let l = true;

            this.attr_arr.forEach(ele => {
              this.form.goods_stock += ele.sku_stock;
              ele.sku_type.forEach(eles => {
                if (eles === "") {
                  this.$message.error("规格值必须填写");
                  l = false;
                }
              });
              if (ele.cover === "") {
                this.$message.error("规格封面必须选择");
                l = false;
              }
              if (ele.sku_stock === 0) {
                this.$message.error("规格库存必须大于0");
                l = false;
              }
            });
            this.specifications.forEach(ele => {
              if (ele.type === "") {
                this.$message.error("规格名必须填写");
                l = false;
              }
            });
            if (l) {
              this.actives = 3;
              return;
            }
          }
          if (this.actives === 3) {
            let prams = {
              goods_id: this.goodsId,
              goods_name: this.form.goods_name,
              goods_type: this.form.goods_type[1],
              goods_cover: this.form.goods_cover.join(","),
              goods_price: this.form.goods_price,
              // cost_rack: this.form.cost_rack,
              goods_original_price: this.form.goods_original_price,
              distribution_type: this.form.distribution_type.join(","),
              templete_id: this.form.templete_id,
              count_sku: JSON.stringify(this.specifications),
              attr_arr: JSON.stringify(this.attr_arr),
              goods_content: this.form.goods_content,
              goods_stock: this.form.goods_stock,
              status: this.form.status,
              tag_id: this.form.tag_id
            };

            SETGOODS(prams).then(res => {
              let { code, msg } = res;
              if (code === 200) {
                this.$emit("out");
              }
              this.$message({
                message: msg,
                type: code === 200 ? "success" : "error"
              });
            });
          }
        }
      });
    },
    async tagList() {
      await TAGLIST({ page: 1, pageshow: 1000000000 }).then(res => {
        let { code, data, msg } = res;
        if (code === 200) {
          this.options = data.list;
        } else {
          this.$message.error(msg);
        }
      });
    },
    async setTag() {
      await this.$refs["formBQ"].validate(valid => {
        if (valid) {
          SETTAG({ name: this.formBQ.name }).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.dialogFormVisibleBQ = false;
              this.tagList();
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        }
      });
    },
    async delTag(id) {
      await this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          DELTAG({ id }).then(res => {
            let { code, msg } = res;
            if (code === 200) {
              this.tagList();
              this.form.tag_id = "";
            }
            this.$message({
              message: msg,
              type: code === 200 ? "success" : "error"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除!"
          });
        });
    },
    close(file) {
      this.showImages = false;
      if (!file) return;
      this.form.goods_cover.push(file.file_path);
    },
    async getPSMS() {
      await SHOWDISTRIBUTIONCONFIGShop().then(res => {
        let { code, data } = res;
        if (code === 200) {
          data.forEach(ele => {
            this.listPSMS.push({ label: ele.label + "", name: ele.name });
          });
        }
      });
    },
    async getMB() {
      await DISTRIBUTIONTEMPLETELIST({ page: 1, pageshow: 101 }).then(res => {
        let { code, data } = res;
        if (code === 200) {
          this.courierLsit = data.list;
          this.courierLsit.some(ele => {
            if (ele.planJson !== null) {
              ele.disarea.push(JSON.parse(ele.planJson));
            }
            if (this.form.templete_id) {
              if (this.form.templete_id === ele.templete_id) {
                this.tableData = ele.disarea;
              }
            } else {
              if (ele.is_default === 1) {
                if (ele.planJson) {
                  ele.planJson = JSON.parse(ele.planJson);
                  ele.disarea.unshift(ele.planJson);
                }
                this.tableData = ele.disarea;
                this.form.templete_id = ele.templete_id;
                this.valuation = ele.valuation;
                return true;
              }
            }
          });
        }
      });
    },
    psTag(e) {
      this.courierLsit.some(ele => {
        if (ele.templete_id === e) {
          this.tableData = ele.disarea;
          this.valuation = ele.valuation;
          return true;
        }
      });
    },
    addF() {
      window.open("/goodsClass?msg=set");
    }
  }
};
</script>
<style lang="scss" scoped>
.commodityImage {
  .icon {
    width: 100px;
    height: 100px;
    border-radius: 6px;
    display: block;
    float: left;
    margin-right: 10px;
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #fff;
    position: relative;
    &:hover {
      .delimg {
        display: inline-block;
      }
    }
    img {
      width: 100px;
      height: 100px;
    }
    .delimg {
      display: none;
      position: absolute;
      top: 4px;
      right: 6px;
      color: #f56c6c;
      cursor: pointer;
    }
  }
  input {
    float: left;
  }
}

.btsample {
  position: relative;
  .sample {
    position: absolute;
    display: none;
    width: 200px;
    height: 200px;
    padding: 10px;
    border-radius: 6px;
    overflow: hidden;
    top: -80px;
  }
  &:hover {
    .sample {
      display: inline-block;
    }
  }
}
.options {
  .l {
    float: left;
  }
  .r {
    float: right;
    color: #8492a6;
    font-size: 18px;
    display: none;
    margin-top: 8px;
  }
  &:hover .r {
    display: inline-block;
  }
}
</style>
